package com.fita.admin.web.controller.data;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.fita.admin.entity.search.currency.ExchangeRateSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataService;
import com.fita.admin.service.data.CurrencyService;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.data.ExchangeRate;
import com.fita.entity.principal.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 汇率管理
 *
 * @author cuteHU
 *
 */
@Controller
@RequestMapping("/currencies")
@MenuSetting("menu-data")
public class CurrencyController {

    private Logger logger = LoggerFactory.getLogger(CurrencyController.class);

    @Autowired
    private CurrencyService currencyService;

    @Autowired
    @Qualifier("dataService")
    private DataService<Principal> principalService;

    /**
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search() {
        return "data/currency/currency-search";
    }

    /**
     * @param search
     * @param page
     * @param request
     * @return
     */
    @MenuSetting("submenu-currency-management")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView onSearch(ExchangeRateSearch search, Page page, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("data/currency/currency-list");

        int totals = currencyService.countSearch(ExchangeRate.class, search.getPreparedFilter(false));
        if (totals > 0) {

            List<ExchangeRate> exchangeRates = currencyService.search(ExchangeRate.class, search, page.with(totals));
            modelAndView.addObject("exchangeRates", exchangeRates);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
        }
        return modelAndView;
    }
    
    /**
     * list current exchange rate.
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-currency-management")
    public ModelAndView listCurrentRate() {
    	
        ModelAndView modelAndView = new ModelAndView("data/currency/current-currency-list");
        
        modelAndView.addObject("isCurrent", true);
                
        List<ExchangeRate> exchangeRates = currencyService.listCurrentRate();
        
        modelAndView.addObject("exchangeRates", exchangeRates);
        
        return modelAndView;
    }
    
    /**
     * list exchange rate.
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "isCurrent=false")
    @MenuSetting("submenu-currency-management")
    public ModelAndView list(Page page, HttpServletRequest request) {
    	
        ModelAndView modelAndView = new ModelAndView("data/currency/currency-list");
        
        modelAndView.addObject("isCurrent", false);
        
        int totals = currencyService.count();
        
        if (totals > 0) {
			
        	List<ExchangeRate> exchangeRates = currencyService.listByPage(ExchangeRate.class, page.with(totals));
        	
        	modelAndView.addObject("exchangeRates", exchangeRates);
        	
        	modelAndView.addObject("page", page);
		}
        modelAndView.addObject("queryString", "isCurrent=false");
        
        return modelAndView;
    }

    /**
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-currency-management")
    public ModelAndView create() {
        ModelAndView modelAndView = new ModelAndView("data/currency/currency-create");
        return modelAndView;
    }

    /**
     * @param exchangeRate
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCreate(@Secure Login login,ExchangeRate exchangeRate) {

        HttpResult httpResult = new HttpResult();

        try {

            currencyService.createCurrency(exchangeRate,login.getId());
            httpResult.success().message("添加汇率成功");

        } catch (BusinessException e) {
            httpResult.fail(e.getCode()).message(e.getMessage());
            logger.error("onCreate occurs error: ", e);

        } catch (Exception e) {
            logger.error("onCreate occurs error: ", e);
            httpResult.fail("500").message("添加汇率失败");
        }

        return httpResult;
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("data/currency/currency-edit");
        
        ExchangeRate exchangeRate = currencyService.load(ExchangeRate.class, id);
        
        modelAndView.addObject("exchangeRate", exchangeRate);
        
        return modelAndView;
        
    }
    
    /**
     * @param id
     * @param exchangeRate
     * @return
     */
    @RequestMapping(value = "/{id}" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@PathVariable(name="id") Long id,
            @Preloading("exchangeRateId") ExchangeRate exchangeRate) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            currencyService.update(exchangeRate);
            
            httpResult.success().message("编辑汇率成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("编辑汇率失败");
            logger.error("#onEdit() - edit fail, exception is [{}]",e);
        }
        
        return httpResult;
        
    }
}
